<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="评价计划" prop="planId">
        <el-select
          v-model="queryParams.planId"
          placeholder="请选择评价计划"
          clearable
          filterable
          class="!w-240px"
        >
          <el-option
            v-for="plan in planList"
            :key="plan.id"
            :label="plan.planName"
            :value="plan.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="参评人员" prop="candidateInfoId">
        <el-select
          v-model="queryParams.candidateInfoId"
          placeholder="请选择参评人员"
          clearable
          filterable
          class="!w-240px"
        >
          <el-option
            v-for="candidate in candidateList"
            :key="candidate.id"
            :label="candidate.name"
            :value="candidate.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否合格" prop="isQualified">
        <el-select
          v-model="queryParams.isQualified"
          placeholder="请选择是否合格"
          clearable
          class="!w-240px"
        >
          <el-option label="合格" :value="true" />
          <el-option label="不合格" :value="false" />
        </el-select>
      </el-form-item>
      <el-form-item label="等级评定" prop="gradeLevel">
        <el-select
          v-model="queryParams.gradeLevel"
          placeholder="请选择等级评定"
          clearable
          class="!w-240px"
        >
          <el-option label="优秀" value="优秀" />
          <el-option label="良好" value="良好" />
          <el-option label="合格" value="合格" />
          <el-option label="不合格" value="不合格" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="handleCalculate"
          v-hasPermi="['eval:score:calculate']"
        >
          <Icon icon="ep:refresh" class="mr-5px" /> 计算成绩
        </el-button>
        <el-button
          type="info"
          plain
          @click="handleBatchCalculate"
          v-hasPermi="['eval:score:calculate']"
        >
          <Icon icon="ep:refresh" class="mr-5px" /> 批量计算
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['eval:score:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 统计卡片 -->
  <el-row :gutter="20" class="mb-4">
    <el-col :span="6">
      <el-card>
        <div class="flex items-center">
          <div class="flex-1">
            <div class="text-2xl font-bold text-blue-600">{{ statistics.totalCount || 0 }}</div>
            <div class="text-gray-500">总人数</div>
          </div>
          <Icon icon="ep:user" class="text-4xl text-blue-600" />
        </div>
      </el-card>
    </el-col>
    <el-col :span="6">
      <el-card>
        <div class="flex items-center">
          <div class="flex-1">
            <div class="text-2xl font-bold text-green-600">{{ statistics.qualifiedCount || 0 }}</div>
            <div class="text-gray-500">合格人数</div>
          </div>
          <Icon icon="ep:check" class="text-4xl text-green-600" />
        </div>
      </el-card>
    </el-col>
    <el-col :span="6">
      <el-card>
        <div class="flex items-center">
          <div class="flex-1">
            <div class="text-2xl font-bold text-red-600">{{ statistics.unqualifiedCount || 0 }}</div>
            <div class="text-gray-500">不合格人数</div>
          </div>
          <Icon icon="ep:close" class="text-4xl text-red-600" />
        </div>
      </el-card>
    </el-col>
    <el-col :span="6">
      <el-card>
        <div class="flex items-center">
          <div class="flex-1">
            <div class="text-2xl font-bold text-orange-600">{{ statistics.qualificationRate || '0%' }}</div>
            <div class="text-gray-500">合格率</div>
          </div>
          <Icon icon="ep:pie-chart" class="text-4xl text-orange-600" />
        </div>
      </el-card>
    </el-col>
  </el-row>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="计划名称" align="center" prop="planName" width="150" />
      <el-table-column label="参评人员" align="center" prop="candidateName" width="100" />
      <el-table-column label="身份证号" align="center" prop="candidateIdNumber" width="180" />
      <el-table-column label="申报职业" align="center" prop="appliedProfession" width="120" />
      <el-table-column label="申报等级" align="center" prop="appliedLevel" width="80" />
      <el-table-column label="总分" align="center" prop="totalScore" width="80">
        <template #default="scope">
          <el-tag :type="getScoreTagType(scope.row.totalScore, 100)">
            {{ scope.row.totalScore }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="加权分" align="center" prop="weightedScore" width="80">
        <template #default="scope">
          <el-tag :type="getScoreTagType(scope.row.weightedScore, 100)">
            {{ scope.row.weightedScore }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="是否合格" align="center" prop="isQualified" width="80">
        <template #default="scope">
          <el-tag :type="scope.row.isQualified ? 'success' : 'danger'">
            {{ scope.row.isQualified ? '合格' : '不合格' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="等级评定" align="center" prop="gradeLevel" width="80">
        <template #default="scope">
          <el-tag :type="getGradeLevelTagType(scope.row.gradeLevel)">
            {{ scope.row.gradeLevel }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="汇总状态" align="center" prop="summaryStatus" width="100">
        <template #default="scope">
          <el-tag :type="getSummaryStatusTagType(scope.row.summaryStatus)">
            {{ getSummaryStatusText(scope.row.summaryStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" width="200" fixed="right">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openDetail(scope.row.id)"
            v-hasPermi="['eval:score:query']"
          >
            详情
          </el-button>
          <el-button
            link
            type="primary"
            @click="handleRecalculate(scope.row.id)"
            v-hasPermi="['eval:score:calculate']"
          >
            重新计算
          </el-button>
          <el-dropdown @command="(command) => handleCommand(command, scope.row)">
            <el-button link type="primary">
              更多<Icon icon="ep:arrow-down" class="ml-5px" />
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="certificate">
                  生成证书
                </el-dropdown-item>
                <el-dropdown-item command="print">
                  打印成绩单
                </el-dropdown-item>
                <el-dropdown-item command="delete">
                  删除
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 详情弹窗 -->
  <SummaryDetail ref="detailRef" />
  
  <!-- 计算成绩弹窗 -->
  <CalculateForm ref="calculateRef" @success="getList" />
</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import { 
  EvalScoreSummaryVO, 
  EvalScoreSummaryPageReqVO, 
  getScoreSummaryPage, 
  deleteScoreSummary, 
  exportScoreSummary,
  calculateScoreSummary,
  batchCalculateScoreSummary
} from '@/api/eval/score'
import { EvalPlanVO, getPlanListByStatus } from '@/api/eval/plan'
import { EvalCandidateInfoVO, getCandidateInfoListByPlanId } from '@/api/eval/candidate/index'
import SummaryDetail from './SummaryDetail.vue'
import CalculateForm from './CalculateForm.vue'

/** 成绩汇总 列表 */
defineOptions({ name: 'EvalScoreSummary' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<EvalScoreSummaryVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const statistics = ref<any>({}) // 统计数据
const queryParams = reactive<EvalScoreSummaryPageReqVO>({
  pageNo: 1,
  pageSize: 10,
  planId: undefined,
  candidateInfoId: undefined,
  isQualified: undefined,
  gradeLevel: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const planList = ref<EvalPlanVO[]>([]) // 计划列表
const candidateList = ref<EvalCandidateInfoVO[]>([]) // 参评人员列表

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await getScoreSummaryPage(queryParams)
    list.value = data.list
    total.value = data.total
    
    // 计算统计数据
    calculateStatistics()
  } finally {
    loading.value = false
  }
}

/** 计算统计数据 */
const calculateStatistics = () => {
  const totalCount = list.value.length
  const qualifiedCount = list.value.filter(item => item.isQualified).length
  const unqualifiedCount = totalCount - qualifiedCount
  const qualificationRate = totalCount > 0 ? ((qualifiedCount / totalCount) * 100).toFixed(1) + '%' : '0%'
  
  statistics.value = {
    totalCount,
    qualifiedCount,
    unqualifiedCount,
    qualificationRate
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  candidateList.value = []
  handleQuery()
}

/** 详情操作 */
const detailRef = ref()
const openDetail = (id: number) => {
  detailRef.value.open(id)
}

/** 计算成绩操作 */
const calculateRef = ref()
const handleCalculate = () => {
  calculateRef.value.open()
}

/** 批量计算成绩 */
const handleBatchCalculate = async () => {
  try {
    await message.confirm('确认批量计算所有计划的成绩汇总？')
    const planIds = planList.value.map(plan => plan.id!)
    await batchCalculateScoreSummary(planIds)
    message.success('批量计算成功')
    await getList()
  } catch {}
}

/** 重新计算单个成绩 */
const handleRecalculate = async (id: number) => {
  try {
    await message.confirm('确认重新计算该成绩汇总？')
    // TODO: 实现重新计算单个成绩的接口
    message.success('重新计算成功')
    await getList()
  } catch {}
}

/** 更多操作 */
const handleCommand = async (command: string, row: EvalScoreSummaryVO) => {
  switch (command) {
    case 'certificate':
      handleGenerateCertificate(row.id!)
      break
    case 'print':
      handlePrintScore(row.id!)
      break
    case 'delete':
      await handleDelete(row.id!)
      break
  }
}

/** 生成证书 */
const handleGenerateCertificate = (id: number) => {
  // TODO: 实现生成证书功能
  message.info('生成证书功能开发中...')
}

/** 打印成绩单 */
const handlePrintScore = (id: number) => {
  // TODO: 实现打印功能
  message.info('打印功能开发中...')
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await deleteScoreSummary(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await exportScoreSummary(queryParams)
    download.excel(data, '成绩汇总.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 获取分数标签类型 */
const getScoreTagType = (score: number, maxScore: number) => {
  const rate = score / maxScore
  if (rate >= 0.9) return 'success'
  if (rate >= 0.8) return 'primary'
  if (rate >= 0.6) return 'warning'
  return 'danger'
}

/** 获取等级评定标签类型 */
const getGradeLevelTagType = (gradeLevel: string) => {
  const typeMap = {
    '优秀': 'success',
    '良好': 'primary',
    '合格': 'warning',
    '不合格': 'danger'
  }
  return typeMap[gradeLevel] || ''
}

/** 获取汇总状态标签类型 */
const getSummaryStatusTagType = (status: number) => {
  const typeMap = { 0: 'warning', 1: 'success' }
  return typeMap[status] || ''
}

/** 获取汇总状态文本 */
const getSummaryStatusText = (status: number) => {
  const textMap = { 0: '待汇总', 1: '已汇总' }
  return textMap[status] || '未知'
}

/** 加载计划列表 */
const loadPlanList = async () => {
  try {
    // 获取进行中和已完成的计划
    const inProgressPlans = await getPlanListByStatus(4)
    const completedPlans = await getPlanListByStatus(5)
    planList.value = [...inProgressPlans, ...completedPlans]
  } catch (error) {
    console.error('加载计划列表失败:', error)
  }
}

/** 初始化 **/
onMounted(() => {
  loadPlanList()
  getList()
})
</script>
